using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

public class MeshBall : MonoBehaviour
{
    // Start is called before the first frame update
    static int baseColorId = Shader.PropertyToID("_BaseColor");
    static int _MetallicId = Shader.PropertyToID("_Metallic");
    static int _SmoothnessId = Shader.PropertyToID("_Smoothness");

    [SerializeField]
    Mesh mesh = default;

    [SerializeField]
    Material material = default;


    Matrix4x4[] matrices = new Matrix4x4[1023];
    Vector4[] baseColors = new Vector4[1023];
    float[] metallics = new float[1023];
    float[] smoothness = new float[1023];

    MaterialPropertyBlock block;

    [SerializeField]
    LightProbeProxyVolume lightProbeVolume = null;

    private void Awake()
    {
        for(int i=0; i < matrices.Length;i++)
        {
            matrices[i] = Matrix4x4.TRS(
                this.transform.position+ Random.insideUnitSphere * 10f,
                Quaternion.Euler(
                    Random.value * 360f,
                    Random.value * 360f,
                     Random.value * 360f
                    ),
                Vector3.one
                );

            baseColors[i] = new Vector4(Random.value, Random.value, Random.value,Random.Range(0.5f, 1f));
            metallics[i] = Random.value < 0.25f ? 1f : 0f;
            smoothness[i] = Random.Range(0.05f, 0.95f);
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(block == null )
        {
            block = new MaterialPropertyBlock();
            block.SetVectorArray(baseColorId, baseColors);
            block.SetFloatArray(_MetallicId, metallics);
            block.SetFloatArray(_SmoothnessId, smoothness);

            var positions = new Vector3[1023];
            for(int i=0; i < matrices.Length; i++)
            {
                positions[i] = matrices[i].GetColumn(3);
            }
            var lightProbes = new SphericalHarmonicsL2[1023];
            var occlusionProbes = new Vector4[1023];
            LightProbes.CalculateInterpolatedLightAndOcclusionProbes(
                positions,
                lightProbes,
                occlusionProbes
                );
            block.CopySHCoefficientArraysFrom(lightProbes);
            block.CopyProbeOcclusionArrayFrom(occlusionProbes);
        }

        Graphics.DrawMeshInstanced(mesh, 0, material, matrices, 1023, block,
            ShadowCastingMode.On,
            true,
            0,
            null,
            lightProbeVolume ? LightProbeUsage.UseProxyVolume: LightProbeUsage.CustomProvided,
            lightProbeVolume
            );
    }
}
